package service

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"wechat01/basic/config"
	"wechat01/handler/model"
	"wechat01/handler/request"
)

func AddFriend(c *gin.Context) {
	var form request.AddFriend
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	userId := c.GetFloat64("userId")
	var friend model.Friend
	if err := friend.IsFriend(config.DB, int(userId), form.FriendId); err == nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "好友已存在"})
		return
	}
	friend = model.Friend{
		UserId:   int(userId),
		FriendId: form.FriendId,
		Remark:   form.Remark,
	}
	if err := friend.AddFriend(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "好友申请失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友申请成功",
	})
	return
}

func FriendApply(c *gin.Context) {
	var form request.FriendApply
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	userId := c.GetFloat64("userId")
	var friend model.Friend
	if err := friend.FriendApply(config.DB, int(userId), form.FriendId, form.Status); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "好友验证错误"})
		return
	}
	switch form.Status {
	case 1:
		friend = model.Friend{
			UserId:   form.FriendId,
			FriendId: int(userId),
			Status:   1,
		}
		err := friend.AddFriend(config.DB)
		if err != nil {
			return
		}
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "已同意添加好友"})
		return
	case 2:
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "已拒绝添加好友"})
		return
	default:
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "待验证"})
		return
	}
}

func SearchFriend(c *gin.Context) {
	var form request.SearchFriend
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	var friend model.Friend
	list, err := friend.SearchFriend(config.DB, form.Keyword)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "搜索好友失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "搜索好友成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}
func GetFriend(c *gin.Context) {
	userId := c.GetFloat64("userId")
	var friend model.Friend
	list, err := friend.GetFriend(config.DB, int(userId))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "查询好友列表失败"})
		return
	}
	key := fmt.Sprintf("friendList_%v", userId)
	cacheList, _ := config.Rdb.Get(config.Ctx, key).Result()
	if cacheList == "" {
		jsonStr, _ := json.Marshal(list)
		config.Rdb.Set(config.Ctx, key, jsonStr, time.Minute*10)
	} else {
		json.Unmarshal([]byte(cacheList), &list)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询好友列表成功",
		"data": gin.H{
			"list": list,
		},
	})
	return
}
